package cn.fudong.bos.realm;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.fudong.bos.domain.system.Permission;
import cn.fudong.bos.domain.system.Role;
import cn.fudong.bos.domain.system.User;
import cn.fudong.bos.service.system.RoleService;
import cn.fudong.bos.service.system.UserService;
import cn.fudong.bos.service.system.PermissionService;

/**
 * 
 * @description:自定义Realm 处理安全的数据
 * @author ：d_fu
 * @date 创建时间：2018年3月30日 下午10:00:35
 *
 */
// @Service("bosRealm")
public class BosRealm extends AuthorizingRealm {

	@Autowired
	private UserService userservice;

	@Autowired
	private RoleService roleService;

	@Autowired
	private PermissionService permissionService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
		System.out.println("shiro 用户授权管理..");
		// 创建一个AuthorizationInfo 把权限加进去
		SimpleAuthorizationInfo AuthorizationInfo = new SimpleAuthorizationInfo();

		// 拿到用户
		Subject subyect = SecurityUtils.getSubject();
		User user = (User) subyect.getPrincipal();
		// 根据用户拿到角色
		List<Role> roles = roleService.findByUser(user);
		for (Role role : roles) {
			AuthorizationInfo.addRole(role.getKeyword());
		}
		// 根据用户查权限
		List<Permission> permissions = permissionService.findByUser(user);
		for (Permission permission : permissions) {
			AuthorizationInfo.addStringPermission(permission.getKeyword());
		}
		return AuthorizationInfo;
	}

	// 认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("开始shiro认证管理..");
		// 转换token
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
		// 根据用户名查用户
		User user = userservice.findByUsername(usernamePasswordToken.getUsername());

		if (user == null) {
			// 用户名不存在
			return null;
		} else {
			// 用户名存在
			// 参数一：principal 需要管理的对象
			// 参数二：credentials
			// 参数三：realm的名字
			// 安全管理器自动比较密码是否一样，不一样会报错
			return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
		}

	}

}
